package org.lql.algo.codecrush.hot100.linked;

import org.lql.algo.common.ListNode;

/**
 * @author: liangqinglong
 * @date: 2025-10-11 13:45
 * @description: 19. 删除链表的倒数第 N 个结点 <a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class RemoveNthFromEnd {

	public ListNode removeNthFromEnd(ListNode head, int n) {
		ListNode dummy = new ListNode(0, head);
		ListNode cur = head;
		int length = 0;
		while (cur != null) {
			length++;
			cur = cur.next;
		}
		cur = dummy;
		for (int i = 0; i < length - n; i++) {
			cur = cur.next;
		}
		cur.next = cur.next.next;
		return dummy.next;
	}

	public static void main(String[] args) {
		ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
		ListNode listNode = new RemoveNthFromEnd().removeNthFromEnd(head, 2);
		while (listNode != null) {
			System.out.print(listNode.val + " -> ");
			listNode = listNode.next;
		}
	}
}
